package com.ljl.ssm.service.impl;

import com.ljl.ssm.entity.Order;
import com.ljl.ssm.entity.OrderItem;
import com.ljl.ssm.mapper.OrderMapper;
import com.ljl.ssm.pojo.OrderExample;
import com.ljl.ssm.pojo.OrderItemExample;
import com.ljl.ssm.service.IOrderItemService;
import com.ljl.ssm.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.logging.Logger;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author BaoZhou
 * @since 2019-07-07
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    IOrderItemService orderItemService;

    @Override
    public Order get(int id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Order> listAll() {
        OrderExample example = new OrderExample();
        return orderMapper.selectByExample(example);
    }

    @Override
    public List<Order> list(Integer user_id, String excludedStatus) {
        OrderExample example = new OrderExample();
        example.or().andUser_idEqualTo(user_id).andStatusNotEqualTo(excludedStatus);
        example.setOrderByClause("id desc");
        return orderMapper.selectByExample(example);
    }

    @Override
    public List<Order> listByUserId(Integer user_id) {
        OrderExample example = new OrderExample();
        example.or().andUser_idEqualTo(user_id);
        return orderMapper.selectByExample(example);
    }

    @Override
    public void update(Order order) {
        orderMapper.updateByPrimaryKey(order);
    }

    @Override
    public void add(Order c) {
        orderMapper.insertBy(c);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackForClassName = "Exception")
    public float add(Order order, List<OrderItem> orderItems) {
        float total = 0;
        add(order);

        // 用来模拟当增加订单后出现异常，观察事务管理是否预期发生
        if (false)
            throw new RuntimeException();

        for (OrderItem oi : orderItems) {
            oi.setOrderId(order.getId());
            orderItemService.update(oi);
            total += oi.getProduct().getPrice() * oi.getNumber();
        }
        return total;
    }
}
